package com.zyl.Ecs.realtime.service.impl;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.zyl.Ecs.common.domain.data.bean.DataBean;
import com.zyl.Ecs.common.exception.EcsException;
import com.zyl.Ecs.common.utils.CUtil;
import com.zyl.Ecs.common.utils.ObjectUtil;
import com.zyl.Ecs.realtime.datasource.Master;
import com.zyl.Ecs.realtime.datasource.Slave;
import com.zyl.Ecs.realtime.mapper.RealTimeMapper;
import com.zyl.Ecs.realtime.service.RealTimeService;
import com.zyl.Ecs.realtime.util.TableUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * @version v1.0
 * @ProjectName: Ecs
 * @Package: com.zyl.Ecs.realtime.service.impl
 * @ClassName: RealTimeServiceImpl
 * @Description TODO
 * @Author 翟玉龙
 * @Date 2024/12/6-10:57
 */
@Service
@RequiredArgsConstructor
public class RealTimeServiceImpl extends MPJBaseServiceImpl<RealTimeMapper, DataBean>
        implements RealTimeService{

    private final RealTimeMapper realtimeMapper;

    /**
     * 插入数据
     *
     * @param dataList 数据列表
     * @throws EcsException 异常
     */
    @Master
    @Override
    public void insert(List<DataBean> dataList) throws EcsException {
        if (ObjectUtil.isEmpty(dataList)) {
            return;
        }
        for (DataBean dataEntity : dataList) {
            handlerInsert(dataEntity);
        }
    }

    /**
     * 获取实时数据
     *
     * @param tableNames 表名
     * @return {@link List }<{@link DataBean }>
     */
    @Override
    @Slave
    public List<DataBean> getRealTimeData(List<String> tableNames) {
        return realtimeMapper.selectLatestData(tableNames);
    }

    /**
     * 写入数据
     *
     * @param dataEntity 数据实体
     */
    private void handlerInsert(DataBean dataEntity) {
        /* 读取采集时间 */
        Long time = dataEntity.getTime();
        /* 转换为LocalDateTime */
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        /* 提取年、月 */
        int year = localDateTime.getYear();
        int month = localDateTime.getMonthValue();
        /* 读取传感器ID */
        Integer sensorId = dataEntity.getSensorId();
        /* 年、月、传感器ID拼接为完整表名 */
        String tableName = TableUtil.tableName(year, month, sensorId);
        /* 执行写入 */
        try {
            realtimeMapper.insert(tableName, dataEntity);
        } catch (Exception e) {
            CUtil.logError(
                    String.format("[Realtime]数据写入失败，表名：%s， 数据值：%s，采集时间：%s，传感器ID：%s，异常：%s",
                            tableName,
                            dataEntity.getValue(),
                            new Date(time),
                            dataEntity.getSensorId(),
                            e.getClass().getName() + ": " + e.getMessage())
            );
        }
    }
}
